﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;

using Ext.Net;
using CF.Data;
using CF.Service;
using Kwan.Data;

namespace CF.Web
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (!X.IsAjaxRequest)
            //{
            //    BaseService<TColumnClass, TColumnClass, string> bs = new BaseService<TColumnClass, TColumnClass, string>();
            //    List<TColumnClass> ArtClassView = bs.EntityDAO.Load(new NameValueCollection());
            //    ColumnClassDS.DataSource = ArtClassView;
            //    ColumnClassDS.DataBind();
            //}
        }

        [DirectMethod(Namespace="Column")]
        public void AfterEdit(string id, string field, string oldValue, string newValue, object customer)
        {
            //List<TColumn> list= JSON.Deserialize<List<TColumn>>(customer);
            TColumn c = JSON.Deserialize<TColumn>(customer.ToString());
            c.EntityState._Loaded = true;
            DBContext.Save(c);
            this.Store1.CommitChanges();
        }

        protected void BtnAddInfo_Click(object sender, EventArgs e)
        {
            NewColumn();
            ShowEditWindow();
        }

        protected void BtnDeleteInfo_Click(object sender, DirectEventArgs e)
        {
            Dictionary<string, string>[] selected = JSON.Deserialize<Dictionary<string, string>[]>(e.ExtraParams["Values"]);
            if (selected.Length <= 0)
            {
                Notification notify = ExtHelper.GetNotification("系统提示", "请至少选择一项！").Show();
                return;
            }
            foreach (Dictionary<string, string> row in selected)
            {
                (TColumn.entityID == row["EntityID"]).Delete<TColumn>();
            }
            Store1.DataBind();
        }

        [DirectMethod(ShowMask = true, Msg = "生成中...")]
        public void CreateFile(string tt)
        {
            CreateFiles cf = new CreateFiles();
            cf.ProjectName = FilterProjectName.Text;
            if (!string.IsNullOrEmpty(FilterProjectName.Text))
            {
                NameValueCollection ps = new NameValueCollection() { { "ProjectName", FilterProjectName.Text } };
                //string hql = "s.ProjectName = :ProjectName and s.TableName = :TableName Order By s.TableName,s.NameEN";
                //Dictionary<string, object> args = new Dictionary<string, object>();
                //args.Add("ProjectName", FilterProjectName.Text);
                IList<TColumn> ProjectList = null;
                if (!string.IsNullOrEmpty(FilterTableName.Text))
                {
                    //args.Add("TableName", FilterTableName.Text);
                    ProjectList =
                        (TColumn.projectName == FilterProjectName.Text & TColumn.tableName == FilterTableName.Text)
                        .List<TColumn>(new Kwan.Data.Region(), new string[] { "NameEN ASC" });
                    if (ProjectList.Count > 0)
                    {
                        cf.TableName = FilterTableName.Text;
                        cf.DoBuild(ProjectList);
                        cf.CreatNewSQLite(FilterProjectName.Text);
                        cf.CreateTable(FilterProjectName.Text, FilterTableName.Text);
                    }
                }
                else
                {
                    //IDatabaseHelper db = DatabaseMgr.Instance.GetDatabaseHelper("");
                    //DataTable tbl = db.LoadDataTable(db.GetSqlStringCommand("select distinct TableName from CF_Column where ProjectName = '" + FilterProjectName.Text + "'"));
                    IList<TColumn> TableList = null;
                    Kwan.Data.Region r=new Kwan.Data.Region() { Start = 0 };
                    using (IConnectinContext cc = DBContext.Context1)
                    {
                        Command cmd = new Command("select distinct * from CF_Column where ProjectName = '" + FilterProjectName.Text + "'");
                        TableList = cc.List<TColumn>(cmd, r);
                    }
                    ProjectList = (TColumn.projectName == FilterProjectName.Text).List<TColumn>(r, new string[] { "NameEN ASC" });
                    TableList = ProjectList.Distinct(p =>
                        p.TableName, StringComparer.CurrentCultureIgnoreCase).ToList<TColumn>();
                    cf.CreatNewSQLite(FilterProjectName.Text);
                    cf.CreateTables(TableList);
                    
                    string CallBack = string.Empty;
                    string CallBackString = "\r\n\t\tpublic string TableName(NameValueCollection ps)\r\n\t\t{\r\n\t\t\tBaseFacade<TTableName, TTableName, int> facade = new BaseFacade<TTableName, TTableName, int>();\r\n\t\t\tfacade.Service.ViewDAO.QueryBuilder = new TableNameQuery();\r\n\t\t\treturn facade.Execute(ps);\r\n\t\t}";
                    foreach (TColumn t in TableList)
                    {
                        cf.isClass = t.TableName.ToLower().Contains("class");
                        int count = TableList.AsQueryable().Where(a => a.TableName == t.TableName + "Class").Count();
                        bool hadClass = count > 0;
                        IList<TColumn> TableFieldList = ProjectList.Where(a => a.TableName == t.TableName).ToList();
                            //(TColumn.projectName == FilterProjectName.Text & TColumn.tableName == t.TableName).List<TColumn>();
                        if (TableFieldList.Count != 0)
                        {
                            cf.TableName = t.TableName;
                            cf.InitModel(hadClass);
                            cf.DoBuild(TableFieldList);
                            CallBack = CallBack + CallBackString.Replace("TableName", t.TableName);
                            string ModelCallBack = FileHelper.ReadFile("ModelCallBack.htm").Replace("ProjectName", FilterProjectName.Text).Replace("CallbackMethod", CallBack);
                            FileHelper.WriteFile(ModelCallBack, string.Format(@"Files\{0}\" + "CallBack.cs", FilterProjectName.Text));
                        }
                    }
                }
            }
        }



        [DirectMethod]
        public void DeleteSelected(string obj)
        {
            string[] list = obj.Split(',');
            (TColumn.entityID == list).Delete<TColumn>();
            Store1.DataBind();
        }

        [DirectMethod]
        public void EditInfo(string id)
        {
            SetColumn(DBContext.Load<TColumn>(id));
            ShowEditWindow();
        }

        protected void RefreshDS(object sender, StoreRefreshDataEventArgs e)
        {
            NameValueCollection ps = new NameValueCollection();
            ps.Set("gridsort", e.Sort);
            ps.Set("dir", e.Dir.ToString());
            
            //搜索项
            ps.Set("ProjectName", FilterProjectName.Text);
            ps.Set("TableName", FilterTableName.Text);

            int pageindex = e.Start / e.Limit;
            Kwan.Data.Region r = new Kwan.Data.Region(pageindex, e.Limit);

            Expression exp = ColumnQuery.MakeSearchWhere(ps);
            IList<TColumn> ListView = exp.List<TColumn>(r, new string[] { e.Sort + " " + e.Dir });

            e.Total = exp.Count<TColumn>();
            Store1.DataSource = ListView;
            Store1.DataBind();
        }

        protected void ShowEditWindow()
        {
            EditWindow.Show();
        }

        protected void NewColumn()
        {
            this.txtID.Text = string.Empty;
            this.txtProjectName.Text = string.IsNullOrEmpty(this.FilterProjectName.Text) ? string.Empty : this.FilterProjectName.Text;
            this.txtTableName.Text = string.IsNullOrEmpty(this.FilterTableName.Text) ? string.Empty : this.FilterTableName.Text;
            this.txtNameEN.Text = string.Empty;
            this.txtNameCN.Text = string.Empty;
            this.txtLength.Text = string.Empty;
            this.txtIsQuery.Checked = true;
            this.txtMemo.Text = string.Empty;

        }

        protected void SetColumn(TColumn tt)
        {
            this.txtID.Text = tt.EntityID.ToString();
            this.txtProjectName.Text = tt.ProjectName;
            this.txtTableName.Text = tt.TableName;
            this.txtNameEN.Text = tt.NameEN;
            this.txtNameCN.Text = tt.NameEN;
            this.txtType.Text = tt.Type;
            this.txtLength.Text = tt.Lenth;
            this.txtIsQuery.Checked = tt.IsQuery;
            this.txtMemo.Text = tt.Memo;
            this.txtField.Value = tt.Field;
        }

        protected void SaveEmployee(object sender, DirectEventArgs e)
        {
            TColumn tt = !string.IsNullOrEmpty(txtID.Text) ?
                (TColumn.entityID == Convert.ToInt32(txtID.Text)).ListFirst<TColumn>() : new TColumn();
            tt.ProjectName = this.txtProjectName.Text;
            tt.TableName = this.txtTableName.Text;
            tt.NameEN = this.txtNameEN.Text;
            tt.NameCN = this.txtNameCN.Text;
            tt.Type = this.txtType.Text;
            tt.Lenth = this.txtLength.Text;
            tt.IsQuery = this.txtIsQuery.Checked;
            tt.Memo = this.txtMemo.Text;
            tt.Field = this.txtField.CheckedItems[0].BoxLabel;
            DBContext.Save(tt);
            this.Store1.DataBind();
            this.EditWindow.Hide();

        }
    }
}